<?php
/**
 * 蜘蛛抓取（使用snoopy）
 */

class Spider_Grabber_Snoopy extends Spider_Grabber_Abstract {

    /**
     * 获取 snoopy
     */
    private function _getSnoopy() {

        try {
            $snoopy = new Snoopy();
            if ($this->_userAgent) {
                if (is_array($this->_userAgent)) {
                    $idx = array_rand($this->_userAgent);
                    $snoopy->agent = $this->_userAgent[$idx];
                } else {
                    $snoopy->agent = $this->_userAgent;
                }
            }
            $snoopy->cookies = array();
            if ($this->_username) {
                $snoopy->user = $this->_username;
                $snoopy->pass = $this->_password;
            }
            if ($this->_timeout) {
                $snoopy->timed_out = $this->_timeout;
            }

            return $snoopy;
        } catch (Exception $e) {
            throw new Spider_Grabber_Exception('snoopy初始化失败'.$e->getMessage(), Spider_Grabber_Exception::E_SPIDER_GRABBER_INIT_ERROR);
        }
    }

    /**
     * 抓取指定链接内容
     * @param <type> $url
     * @param <type> $cookie
     * @param <type> $httpHeader
     * @return <type>
     */
    public function fetchSource($url, $cookie = null, $httpHeader = null, $ignoreCache = false) {

        if (!$ignoreCache && false !== ($content = $this->_fetchCache($url))) {
            return $content;
        }

        $snoopy = $this->_getSnoopy();
        if ($cookie) {
            $snoopy->cookies = $cookie;
        }
        if ($httpHeader && is_array($httpHeader)) {
            $snoopy->rawheaders = $httpHeader;
        }
        if ($snoopy->fetch($url)) {
            $this->_saveCache($url, $snoopy->results);
            return $snoopy->results;
        }
        return null;
    }
}
